﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSScriptControl;
using System.IO;

namespace Util
{
   public  class JsController
    {
        private static JsController instance;
        public static JsController Instance
        {
            get 
            {
                if (instance == null) 
                {
                    instance = new JsController();
                }
                return instance;
            }
        }

        private ScriptControl control;
        public JsController()
        {
            control = new ScriptControl();
            control.UseSafeSubset = true;
            control.Language = "javascript";
        }
        public ScriptControl LoadJsFileInDir(DirectoryInfo jsDir)
        {
            FileInfo[] jsFiles = jsDir.GetFiles("*.js", SearchOption.AllDirectories);
            foreach (FileInfo fileInfo in jsFiles)
            {
                control = LoadJsfile(fileInfo);
            }
            return control;
        }

        public ScriptControl LoadJsfile(FileInfo jsFile)
        {
            string jsCode = File.ReadAllText(jsFile.FullName);
            return AddJsCode(jsCode);
        }
        public ScriptControl AddJsCode(string jsCode)
        {
            control.AddCode(jsCode);
            return control;
        }

        public object Run(string produceName, params object[] paramters)
        {
            return control.Run(produceName, paramters);
        }

    }
}
